<template>
    <div>
        <div style="margin: 10px 0">
            <el-form :model="pagequery" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="用户名称" prop="title">
                    <el-input
                            v-model="pagequery.userName"
                            placeholder="请输入用户名称"
                            clearable
                            style="width: 240px;"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="用户邮箱" prop="title">
                    <el-input
                            v-model="pagequery.email"
                            placeholder="请输入用户邮箱"
                            clearable
                            style="width: 240px;"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="操作时间">
                    <el-date-picker
                            v-model="dateRange"
                            style="width: 240px"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="dateFormat"
                            :default-time="['00:00:00', '23:59:59']"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="load">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="margin: 10px 0">
            <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
            >新增
            </el-button>
            <el-popconfirm
                    class="ml-5"
                    confirm-button-text='确定'
                    cancel-button-text='我再想想'
                    icon="el-icon-info"
                    icon-color="red"
                    title="您确定批量删除这些数据吗？"
                    @confirm="handleDelete"
            >
                <el-button style="margin: 0 5px" size="mini" type="danger" icon="el-icon-delete" plain slot="reference">
                    批量删除
                </el-button>
            </el-popconfirm>
        </div>

        <el-table v-loading="loading" @selection-change="handleSelectionChange" :data="tableData" border stripe
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="用户编号" width="80" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="username" label="用户名" width="100" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="nickname" label="用户昵称" width="120" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="role"
                             label="角色"
                             width="240">
                <template slot-scope="scope">
                    <div slot="reference" class="name-wrapper">
                        <el-tag style="margin-left: 5px" v-for="item in scope.row.role" size="medium">{{
                                item.name
                            }}
                        </el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="email" width="160" label="邮箱" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="phonenumber" width="120" label="电话" :show-overflow-tooltip="true"></el-table-column>
            <!--            <el-table-column prop="address" label="地址"></el-table-column>-->
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            @click="handleEdit(scope.row)"
                            slot="reference"><i class="el-icon-edit"></i>编辑
                    </el-button>
                    <el-popconfirm
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定删除吗？"
                            @confirm="handleDelete(scope.row)"
                    >
                        <el-button style="margin: 0 10px" size="mini"
                                   type="text"
                                   slot="reference"><i class="el-icon-delete"></i>删除
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pagequery.pageNum"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pagequery.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="title" :visible.sync="dialogFormVisible" width="30%">
            <el-form ref="userForm" :model="form" :rules="rules" label-width="80px" size="small">
                <el-form-item prop="username" label="用户名">
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="roleid" label="角色">
                    <el-select v-model="form.roleid" multiple placeholder="请选择角色">
                        <el-option
                                v-for="item in roles"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="nickname" label="昵称">
                    <el-input v-model="form.nickname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="form.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="phonenumber" label="电话">
                    <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="form.address" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {getUsersPage, addUser, delUserById, getUser, updateUser} from '@/api/system/user'
    import {getAllRoles} from '@/api/system/role'

    export default {
        components: {},
        props: {},
        data() {
            return {
                dateRange: '',
                // 遮罩层
                loading: true,
                title:'',
                dialogFormVisible: false,//新增的对话框
                form: {},//新增的表单
                roles: [],//角色
                tableData: [],//表格数据
                total: 0,
                ids: [],//删除传递id
                pagequery: {  //分页查询条件
                    pageNum: 1,
                    pageSize: 5,
                    username: "",
                    email: "",
                    address: "",
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ],
                    nickname: [
                        {required: true, message: '请输入昵称', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '邮箱不能为空', trigger: 'blur'},
                        {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']}
                    ],
                    phonenumber: [
                        {required: true, message: '电话不能为空', trigger: 'blur'},
                        {pattern: /^((0\d{2,3}-\d{7,8})|(1[345789]\d{9}))$/, message: '请输入正确的手机号码'}
                    ],
                    roleid: [
                        {required: true, message: '请选择角色', trigger: 'blur'},
                    ],
                }
            };
        },
        computed: {},
        watch: {},
        methods: {
            //新增对话框的初始化
            load() {
                this.loading = true
                getUsersPage(this.pagequery).then(res => {
                    this.total = res.data.total
                    this.tableData = res.data.records
                    getAllRoles().then(res => {
                        this.roles = res.data
                    })
                    this.loading = false
                })

            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const userIds = row?.id || this.ids;
                if (userIds.length <= 0) {
                    this.$message.warning("请选择删除的用户")
                    return
                }
                delUserById(userIds).then(res => {
                    if (res.code === 200) {
                        this.$message.success("删除成功")
                        this.load();
                    }
                })
            },
            reset() {
                this.dateRange = ''
                this.pagequery = {
                    pageNum: 1,
                    pageSize: 5,
                    username: "",
                    email: "",
                    address: "",
                }
                this.load()
            },
            handleSizeChange(pageSize) {
                this.pagequery.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                this.pagequery.pageNum = pageNum
                this.load()
            },
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["userForm"].validate(valid => {
                    if (valid) {
                        if (this.form.id != undefined) {
                            updateUser(this.form).then(res => {
                                if(res.code===200){
                                    this.$message.success("修改成功");
                                    this.dialogFormVisible = false;
                                    this.load();
                                }
                            });
                        } else {
                            addUser(this.form).then(res => {
                                if(res.code===200){
                                    this.$message.success("新增成功");
                                    this.dialogFormVisible = false;
                                    this.load();
                                }
                            });
                        }
                    }
                });
            },
            //编辑对话框初始化
            handleAdd() {
                this.title='添加用户'
                this.dialogFormVisible = true
                this.form = {}
            },
            //修改
            handleEdit(row) {
                const userId = row.id
                getUser(userId).then(response => {
                    this.form = response.data
                    this.title = '修改用户'
                });
                this.dialogFormVisible = true
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.load();
            },
            //获取时间区间方法
            dateFormat(picker) {
                this.pagequery.startTime = picker[0]
                this.pagequery.endTime = picker[1]
            },
        },
        created() {
            this.load()
        },
    };
</script>
<style scoped>

</style>
